layui.define(['setter', 'eventHandler', 'layer', 'form', 'AppHelper'], function (experts) {
    var eventHandler = layui.eventHandler
        , setter = layui.setter
        , form = layui.form
        , layer = layui.layer
        , AppHelper = layui.AppHelper
        , Jquery = layui.$
    ;

    var zTreeObj;

    Jquery.getScript(layui.setter.base + "/3prt/zTree_v3/js/jquery-1.4.4.min.js", function () {
        Jquery.getScript(layui.setter.base + "/3prt/zTree_v3/js/jquery.ztree.all.js", function () {

            function TreeMenu(options) {
                var that = this;
                eventHandler.call(that);
                that.constructor = TreeMenu;

                //zTree对象
                that.obj = null;
                //当前选中节点
                that.currentNode = null;

                //触发选中事件并设置当前节点数据
                that.onSelect = function (event, treeId, treeNode) {
                    that.currentNode = treeNode;
                    that.obj.selectNode(that.currentNode);
                    that.fire("select", that.currentNode)
                };

                that.icon = layui.setter.base + "/3prt/imgs/";


                //配置
                that.config = {
                    elem: ""
                    , nodes: []
                    , parentLevel: 4 //默认父级层数
                    , edit: {
                        addNode: true
                        , addChildNode: true
                        , movePrev: true
                        , moveNext: true
                        , remove: true
                        , showToolBar: true
                    }
                    , treeConfig: {
                        edit: {
                            enable: true
                            , showRenameBtn: false
                            , showRemoveBtn: true
                            , removeTitle: "删除"
                            , drag: {
                                inner: false
                                , prev: false
                                , next: false
                            }
                        }
                        , view: {
                            selectedMulti: false
                        }
                        , callback: {
                            beforeRemove: function (treeId, treeNode) {
                                var userConfirm = window.confirm("删除后不可恢复，您确认要删除该项吗？")

                                if (userConfirm) {
                                    var result = that.fire("beforeRemove", treeNode);
                                    return result;
                                }
                                return false;
                            }
                            , onRemove: function (event, treeId, treeNode) {
                                if (that.currentNode == treeNode) {
                                    that.currentNode = null;
                                }
                                that.fire("deleteNode", treeNode);
                                //如果没有节点，则显示提示
                                var nodes = that.obj.getNodes()
                                console.log(nodes);
                                if (!nodes) {
                                    that.showTips();
                                }
                            }
                            , onClick: function (event, treeId, treeNode) {
                                that.onSelect(event, treeId, treeNode);
                            }
                            , onDblClick: function (event, treeId, treeNode) {
                                that.onSelect(event, treeId, treeNode);
                            }
                            , onRename: function (event, treeId, treeNode) {
                                // onSelect(event, treeId, treeNode);
                                that.fire("rename", treeNode)
                            }
                            , onDrop: function (event, treeId, treeNodes, targetNode, moveType) {
                                var params = {
                                    treeId: treeId
                                    , treeNodes: treeNodes
                                    , target: targetNode
                                    , moveType: moveType

                                }
                                switch (moveType) {
                                    case "inner":
                                        that.fire("moveInner", params);
                                        break;
                                    case "prev":
                                        that.fire("movePrev", params);
                                        break;
                                    case "next":
                                        that.fire("moveNext", params);
                                        break;
                                }

                                that.fire("afterDrag", params);
                                return true;
                            }
                        }
                    }
                }

                that.config = $.extend(true, {}, that.config, options);
                that.config.treeConfig.edit.showRemoveBtn = that.config.edit.remove;
            }

            // 创建一个没有实例方法的类
            (function () {
                var Super = function () {
                };
                Super.prototype = eventHandler.prototype;
                //将实例作为子类的原型
                TreeMenu.prototype = new Super();
            })();

            /**
             * 初始化方法
             */
            TreeMenu.prototype.init = function () {
                var that = this;
                var zTreeId = "tree_" + new Date().getTime();

                var dom = $('<div class="layui-card"></div>');
                var btnGroup = $('<div class="layui-card-header"></div>');
                var btns = $('<div class="layui-btn-group"></div>');
                var container = $('<div class="layui-card-body tree-container">\n' +
                    '                        <p class="layui-text tips" style="display: none;">暂无节点，请新建</p>\n' +
                    '                        <ul class="ztree-root ztree" id="' + zTreeId + '"></ul>\n' +
                    '                    </div>\n')

                if (that.config.edit.addNode) {
                    btns.append('<button class="layui-btn layui-btn-xs addNode">添加同级</button>');
                }
                if (that.config.edit.addChildNode) {
                    btns.append('<button class="layui-btn layui-btn-xs layui-btn-normal addChildNode">添加子级</button>');
                }
                if (that.config.edit.movePrev) {
                    btns.append('<button class="layui-btn layui-btn-xs layui-btn-primary movePre">上移</button>');
                }
                if (that.config.edit.moveNext) {
                    btns.append('<button class="layui-btn layui-btn-xs layui-btn-primary moveNext">下移</button>');
                }
                btnGroup.append(btns);

                if (that.config.edit.showToolBar) {
                    dom.append(btnGroup);
                }

                dom.append(container);

                //准备dom元素
                var root = $(that.config.elem);
                root.html(dom);

                //初始化zTree
                var zTree = $("#" + zTreeId);
                zTreeObj = $.fn.zTree.init(zTree, that.config.treeConfig, that.config.nodes);
                that.obj = zTreeObj;

                //绑定新建节点事件
                Jquery(root.find(".addNode")).off("click").on("click", function () {
                    that.addNode()
                });

                //绑定新建节点事件
                Jquery(root.find(".addChildNode")).off("click").on("click", function () {
                    that.addChildNode()
                })

                //绑定上移节点事件
                Jquery(root.find(".movePre")).off("click").on("click", function () {
                    that.movePrev();
                })

                //绑定下移节点事件
                Jquery(root.find(".moveNext")).off("click").on("click", function () {
                    that.moveNext();
                })

                //如果没有默认值则显示提示信息
                if (that.config.nodes.length == 0) {
                    that.showTips();
                }
            }

            TreeMenu.prototype.movePrev = function () {
                var that = this;
                var targetNode = that.currentNode.getPreNode();
                var node = that.move(targetNode, "prev");
                if (node != null) {
                    that.fire("movePrev", {target: targetNode, treeNodes: [node]})
                }
            }

            TreeMenu.prototype.moveNext = function () {
                var that = this;
                var targetNode = that.currentNode.getNextNode();
                var node = that.move(targetNode, "next");
                if (node != null) {
                    that.fire("moveNext", {target: targetNode, treeNodes: [node]})
                }
            }

            TreeMenu.prototype.move = function (targetNode, forward) {
                var that = this;
                if (!that.currentNode) {
                    layer.alert("请选择一个节点进行移动", {icon: 0});
                    return;
                }
                debugger
                if (targetNode != null) {
                    return that.obj.moveNode(targetNode, that.currentNode, forward);
                } else {
                    return null;
                }
            }

            TreeMenu.prototype.updateNode = function (node) {
                var that = this;
                that.obj.updateNode(node);
            }

            TreeMenu.prototype.showTips = function () {
                var that = this;
                Jquery(that.config.elem).find(".tips").show();
                that.fire("showTips", {});
            }

            TreeMenu.prototype.hideTips = function () {
                var that = this;
                Jquery(that.config.elem).find(".tips").hide();
                that.fire("hideTips", {});
            }

            TreeMenu.prototype.checkParentLevel = function (parentNode) {
                var that = this;
                var result = true;
                //检查父级层数
                var parentLevel = that.config.parentLevel;
                if (parentLevel < 0) {
                    layer.alert("父级层数不能小于0", {icon: 0});
                    result = false;
                }
                var selfParent = parentNode; //父节点
                var index = 0;   //是否继续执行
                while (selfParent) {
                    selfParent = selfParent.getParentNode();
                    index++;
                }

                //如果迭代层数大于限制，则给出提示并阻止程序执行
                if (index > parentLevel) {
                    layer.alert("父级层数只能为" + parentLevel, {icon: 0});
                    result = false;
                }
                return result;
            }

            TreeMenu.prototype.newNode = function (parentNode) {
                var that = this;

                if (!that.checkParentLevel(parentNode)) {
                    return;
                }

                var passParams = {parentNode: parentNode, next: true};
                that.fire("beforeAdd", passParams);
                if (!passParams.next) {
                    return;
                }

                var addNodeDom = '<div class="tree-layer-form" id="addNodeFormWrap">\n' +
                    '        <div class="layui-form" lay-filter="addNodeForm" id="addNodeForm">\n' +
                    '            <div class="layui-form-item">\n' +
                    '                <label class="layui-form-label required">节点名称</label>\n' +
                    '                <div class="layui-input-inline" style="width: 190px;">\n' +
                    '                    <input type="text" class="layui-input" name="nodeName"  lay-verify="required" lay-verType="tips">\n' +
                    '                </div>\n' +
                    '                <div class="layui-input-inline" style="width: 80px;">\n' +
                    '                    <button class="layui-btn" lay-submit lay-filter="submitAddNode">保存</button>\n' +
                    '                </div>\n' +
                    '            </div>\n' +
                    '        </div>\n' +
                    '    </div>'

                var topWin = AppHelper.getTopWindow();
                // 弹出新建窗口
                layer.open({
                    type: 1
                    , title: "新建节点"
                    , area: "440px"
                    , content: addNodeDom
                    , success: function (layero, index) {
                        console.log(layui.form)
                        layui.form.render();
                        layui.form.on("submit(submitAddNode)", function (obj) {
                            console.log(obj);
                            var field = obj.field;

                            //隐藏提示
                            that.hideTips();

                            layer.close(index);
                            that.add(parentNode, field.nodeName);

                            return false;
                        })
                    }

                })

            }

            TreeMenu.prototype.add = function (parentNode, name, customField) {
                var that = this;
                var newNodes = that.obj.addNodes(parentNode, [{
                    name: name,
                    nodeType: "REVIEW_ITEM"
                    // icon: that.icon + "REVIEW_ITEM.png"
                }]);
                //执行新建事件
                var currentNode = newNodes[0];


                //触发新建事件
                that.fire("add", {
                    parentNode: parentNode,
                    name: name,
                    customField: customField
                    , currentNode: currentNode
                });

                //返回新建的节点
                return currentNode;
            }

            TreeMenu.prototype.selectNode = function (node) {
                this.currentNode = node;
                this.obj.selectNode(this.currentNode);
                this.fire("select", this.currentNode);
            }

            TreeMenu.prototype.selectedByDefault = function (id) {
                var node = zTreeObj.getNodeByParam("id", id);
                if (node != null) {
                    zTreeObj.checkNode(node, true)
                }
            };

            TreeMenu.prototype.addChildNode = function () {
                var that = this;
                that.newNode(that.currentNode);
            }

            TreeMenu.prototype.addNode = function () {
                var that = this;
                var parentNode = null;
                if (that.currentNode != null) {
                    parentNode = that.currentNode.getParentNode();
                }
                that.newNode(parentNode);
            }

            TreeMenu.prototype.getCurrentNode = function () {
                return this.currentNode;
            }

            TreeMenu.prototype.delNode = function (node) {
                var that = this;
                that.obj.removeNode(that.getCurrentNode());
                var nodes = that.obj.getNodes()
                console.log(nodes);
                if (!nodes) {
                    that.showTips();
                }
            }

            TreeMenu.prototype.getCheckedNodes = function () {
                return this.obj.getCheckedNodes(true);
            }

            /**
             * 展开所有节点
             * @param isExpand
             */
            TreeMenu.prototype.expandAll = function (isExpand) {
                this.obj.expandAll(isExpand);
            }

            /**
             * 获取所有叶子节点
             */
            TreeMenu.prototype.getAllLeafNodes = function () {
                var that = this;
                var allRootNodes = that.obj.getNodes();
                var nodes = that.obj.transformToArray(allRootNodes);
                var leafNodes = [];
                for (var i = 0; i < nodes.length; i++) {
                    var node = nodes[i];
                    if (!node.children || node.children.length == 0) {
                        leafNodes.push(node);
                    }
                }
                return leafNodes;
            }

            TreeMenu.prototype.getAllNodes = function () {
                var that = this;
                var allRootNodes = that.obj.getNodes();
                var nodes = that.obj.transformToArray(allRootNodes);
                return nodes;
            }

            experts("treeMenu", {
                render: function (menuId, nodes, edit) {
                    var zNodes = [];
                    var treeMenu = new TreeMenu({
                        elem: menuId
                        , nodes: nodes
                        , edit: edit
                    });
                    treeMenu.init();
                    return treeMenu;

                },
                customRender: function (options) {
                    var treeMenu = new TreeMenu(options);
                    treeMenu.init();
                    return treeMenu;
                }
            })
        })
    })
}).link(layui.setter.base + "/3prt/zTree_v3/css/zTreeStyle/zTreeStyle.css");
